<?php
/**
 * Created by PhpStorm.
 * User: 江桥
 * QQ：1062241667
 * Date: 2016/9/20
 * Time: 10:09
 */

namespace Admin\Controller;

use Think\Controller;

class ScanOrderController extends CommonController
{	
	public function save_weight(){
		$param=I('param.','','trim');
		$id=$param['id'];
		$pack_weight=$param['pack_weight'];
		$data['pack_weight']=$pack_weight;
		$m=M('Packing',C('DB_PRS'),C('DB_DEPOT'));
		$status=$m->where(array('id'=>$id))->save($data);
		if($status!==false){
			alert_json(1,'修改成功');
		}else{
			alert_json(0,'修改失败');
		}
		
	}
	public function packing_list(){
		$this->display();
	}
		//导出历史包裹列表
	//按商品详细来导
	public function export_get_data(){
		$param=I('param.','','trim');
		$m=M('Packing',C('DB_PRS'),C('DB_DEPOT'));
		$g=M('Pushordergoods',C('DB_PRS'),C('DB_DEPOT'));
		$p=M('Pushorder',C('DB_PRS'),C('DB_DEPOT'));
		
		$map=array();
		$map_p=array();
		$logistics_no=$param['logistics_no'];
		$user_name=$param['user_name'];
		$start_time=$param['start_time'];
		$end_time=$param['end_time'];
		
		!empty($start_time)?$start_time = $start_time:$start_time=0;
		!empty($end_time)?$end_time = $end_time:$end_time =date('Y-m-d',time()+86400);

		$map['_string'] = "created_at>='$start_time' AND created_at<='$end_time'";

		!empty($logistics_no)?$map_p['p.logistics_no']=array('like','%'.$logistics_no.'%'):'';
		!empty($user_name)?$map_p['p.user_name']=array('like','%'.$user_name.'%'):'';
		
		$sql=$p->alias("p")->field("p.order_no,p.logistics_no,g.goods_name,g.goods_no,g.goods_nums")->join("__PUSHORDERGOODS__ g on p.id=g.order_id")->where($map_p)->select(false);
		
		$sql_exec="select aa.order_no,concat(' ',aa.logistics_no) logistics_no,pa.pack_weight,concat(' ',aa.goods_no) goods_no,aa.goods_name,aa.goods_nums,pa.created_at from (".$sql.") aa inner join ".C('DB_PRS')."packing pa on aa.order_no=pa.order_no where 1=1 and ".$map['_string']." order by created_at";
		// echo $sql_exec;
		// die;
		$info=M("",C('DB_PRS'),C('DB_DEPOT'))->query($sql_exec);
		// dump($info);
		// die;
		$xlsName  = "历史包裹列表";
		$xlsCell  = array(
			// array('id','ID'),
			array('order_no','订单编号'),
			array('logistics_no','运单号'),
			array('user_name','收件人姓名'),
			array('pack_weight','包裹重量'),
			array('created_at','订单接收时间'),
			array('goods_no','商品编码'),
			array('goods_name','商品名称'),
			array('goods_nums','商品数量')
		);
		exportExcel($xlsName,$xlsCell,$info);
		die;
		
	}
	//历史包裹列表
	public function get_data(){
		$param=I('param.','','trim');
		$m=M('Packing',C('DB_PRS'),C('DB_DEPOT'));
		$g=M('Pushordergoods',C('DB_PRS'),C('DB_DEPOT'));
		// $p=M('Pushorder',C('DB_PRS'),C('DB_DEPOT'));
		$ck=A('CheckInput');
		
		$map=array();
		$logistics_no=$param['logistics_no'];
		$user_name=$param['user_name'];
		$start_time=$param['start_time'];
		$end_time=$param['end_time'];
		
		!empty($start_time)?$start_time = $start_time:$start_time=0;
		!empty($end_time)?$end_time = $end_time:$end_time =date('Y-m-d',time()+86400);

		$map['_string'] = "created_at>='$start_time' AND created_at<='$end_time'";
		
		//导出Excel
		$excel=I('excel');
		
		!empty($logistics_no)?$map['p.logistics_no']=array('like','%'.$logistics_no.'%'):'';
		!empty($user_name)?$map['p.user_name']=array('like','%'.$user_name.'%'):'';
		
		$page=$ck->in('当前页','page','intval','1',0,0);   
        $rows=$ck->in('每页记录数','rows','intval','',0,0);  
		
        //排序
        $sort=$ck->in('排序','sort','cnennumstr','id',0,0);
        $order=$ck->in('规则','order','cnennumstr','desc',0,0);
		
		$count=$m->where($map)->count();
		$info=$m->field('m.id id,m.order_no,p.logistics_no,p.user_name,p.id pid,m.pack_weight,m.created_at')
				->alias('m')
				->join('__PUSHORDER__ p on m.order_no=p.order_no')
				->where($map)
				->page($page,$rows)
				->order('m.'.$sort.' '.$order)
				->select();
		// echo $m->getlastsql();
		// die;
		foreach($info as $k=>$v){
			$maps['order_id']=$v['pid'];
			$goods_list=$g->where($maps)->select();
			$info[$k]['goods_list']=$goods_list;
			if(!empty($excel)){ //导出Excel
				$info[$k]['logistics_no']=" ".$v['logistics_no'];//转字符串
				$goods_no="";
				$goods_name="";
				$goods_nums="";
				foreach($goods_list as $keyss=>$valuess){
					if($keyss){
						$goods_no.='/'.$valuess['goods_no'];
					}else{
						$goods_no.=" ".$valuess['goods_no'];
					}
					if($keyss){
						$goods_name.='/'.$valuess['goods_name'];
					}else{
						$goods_name.=$valuess['goods_name'];
					}
					if($keyss){
						$goods_nums.='/'.$valuess['goods_nums'];
					}else{
						$goods_nums.=$valuess['goods_nums'];
					}
				}
				$info[$k]['goods_no']=$goods_no;//商品编码
				$info[$k]['goods_name']=$goods_name;//商品名称
				$info[$k]['goods_nums']=$goods_nums;//商品数量
			}
		}
			
		if(!empty($excel)){ //导出Excel
			$xlsName  = "历史包裹列表";
			$xlsCell  = array(
				array('id','ID'),
				array('order_no','订单编号'),
				array('logistics_no','运单号'),
				array('user_name','收件人姓名'),
				array('pack_weight','包裹重量'),
				array('created_at','添加时间'),
				array('goods_no','商品编码'),
				array('goods_name','商品名称'),
				array('goods_nums','商品数量')
			);
			exportExcel($xlsName,$xlsCell,$info);
			die;
		}
		// echo $m->getlastsql();
		if(!empty($info)){
            $data['total']=$count;
            $data['rows']=$info;
        }else{
            $data['total']=0;
            $data['rows']=0;
        }
		
        $this->ajaxReturn($data);
	}
	//根据设置返回对应订单号
	public function mailno_status($order_no){
		$mailno_status=C('base_config.mailno_status');
		if($mailno_status==1 or $mailno_status==2){
			C('scanorder.lang_name','面单');
			if(empty($order_no)){
				return alert('0','请输入面单号');
			}
			$porder_info=M("Pushorder",C('DB_PRS'),C('DB_DEPOT'))->where(array('logistics_no'=>$order_no))->find();

			if(!empty($porder_info)){
				return $porder_info['order_no'];
			}else{
				return alert('0','当前面单号找不到对应商品');
			}
		}else{
			C('scanorder.lang_name','订单');
			if(empty($order_no)){
				return alert('0','请输入订单号');
			}
			return $order_no;
		}
	}
    public function index()
    {	
		$mailno_status=C('base_config.mailno_status');
		if($mailno_status==1){
			C('scanorder.lang_name','面单');
			$sao_no='面单';
		}else if($mailno_status==2){
			C('scanorder.lang_name','面单');
			$sao_no='波次单';
		}else{
			C('scanorder.lang_name','订单');
			$sao_no='订单';
		}
		
		$this->assign('sao_no',$sao_no);
		$this->assign('basket_nums',C('base_config.basket_nums'));
        $this->display();
    }
	public function index_iframe(){
		$this->display();
	}
	public function packing_iframe(){
		$this->display();
	}
	public function weighting_iframe(){
		$this->display();
	}
	//扫描波次单，获得商品数据
	public function get_picklist_goods(){
		$m=M("Picklist",C('DB_PRS'),C('DB_DEPOT'));
		$n=M("Pickorder",C('DB_PRS'),C('DB_DEPOT'));
		$p=M("Pushorder",C('DB_PRS'),C('DB_DEPOT'));
		$g=M("Pushordergoods",C('DB_PRS'),C('DB_DEPOT'));
		$orderno = trim(I('orderno'));
		$n_list=$n->field('p.id,p.order_no,p.logistics_no,p.box_no')->alias('n')->join('__PUSHORDER__ p on n.order_id=p.id')->where(array('n.picklist_no'=>$orderno))->select();

		if(empty($n_list)){
			echo json_encode(array('flag'=>0,'data'=>'没有查到此波次单数据'));
			exit;
		}
		foreach($n_list as $k=>$v){
			$g_list=$g->alias('g')->field('g.goods_name,g.goods_nums,gg.bar_code')->join("__GOODS__ gg on g.goods_no=gg.goods_no",'LEFT')->where(array('g.order_id'=>$v['id']))->select();
			// echo $g->getlastsql();
			// die;
			$n_list[$k]['goods_list']=$g_list;
			if(empty($g_list)){
				echo json_encode(array('flag'=>0,'data'=>'面单号'.$v['logistics_no'].'没有商品数据！'));
				exit;
			}
		}
		
		echo json_encode(array('flag'=>1,'data'=>$n_list));
		exit;
	}
    public function get_goods()
    {
        $orderno = I('orderno');
		$orderno=$this->mailno_status($orderno);
		
        if ($orderno == '') {
            return alert_message('0', '请输入'.C('scanorder.lang_name').'信息');
        }
        $info=M("Pushorder",C('DB_PRS'),C('DB_DEPOT'))->field('id,box_no,logistics_no')->where("order_no='$orderno'")->find();
		$id=$info['id'];
        $result =M("Pushordergoods",C('DB_PRS'),C('DB_DEPOT'))->join("__GOODS__ on __PUSHORDERGOODS__.goods_no=__GOODS__.goods_no",'LEFT')->where("order_id='$id'")->select();
		
		if(C('base_config.mailno_status')==1 or C('base_config.mailno_status')==2){
			$order_no=$info['logistics_no'];//面单号
		}else{
			$order_no=$orderno;//订单号
		}
        if($result){
			echo json_encode(array('flag'=>1,'data'=>$result,'box_no'=>$info['box_no'],'order_no'=>$order_no));
			exit;
        }
        else{
            return alert('0','当前'.C('scanorder.lang_name').'号找不到对应商品');
        }
    }

    public function post_goods()
    {//将信息提交到数据库、、记录订单号和筐号
        if (!IS_POST) {
            die;
        }
        $orderno = I("post.orderno");
        $kno = I("post.kno");
        $orderno = explode(',', $orderno);
        $kno = explode(',', $kno);
        if ($orderno == '' || $kno == '' || count($orderno) != count($kno)) {
            return alert('0', '操作有误');
        }
        foreach ($kno as $k => $v) {
            $data[] = array('pack_num' => $kno[$k], 'order_id' => $orderno[$k]);
        }
        ///////订单号验证、、、存在，则返回错误
        $map['order_id'] = array('in', $orderno);
        if (M("packlist",C('DB_PRS'),C('DB_DEPOT'))->where($map)->count() > 0) {
            return alert('0', '该条记录已经存在');
        }
        if (M('packlist',C('DB_PRS'),C('DB_DEPOT'))->addAll($data)) {
            return alert('1', '操作成功');
        }
        return alert('0', '操作失败');
    }

    //////////打包//////////
    public function packing()
    {
		$mailno_status=C('base_config.mailno_status');
		if($mailno_status==1){
			C('scanorder.lang_name','面单');
		}else{
			C('scanorder.lang_name','订单');
		}
		$pm = M("PackageMaterial",C('DB_PRS'),C('DB_DEPOT'));
		$pm_info=$pm->where(array('default'=>1))->find();
		if(!empty($pm_info)){
			$this->assign('material_no',$pm_info['pn']);
		}
        $this->display();
    }

    //扫描  验证当前订单是否已退货（拦截，暂不开发）  以及订单是否存在
    public function paking_order()
    {
		$P = M("Packing",C('DB_PRS'),C('DB_DEPOT'));
		$orderno = I("get.index");
		$orderno=$this->mailno_status($orderno);
        if($P->where("order_no='{$orderno}'")->count()>=1){
            alert(3,'该'.C('scanorder.lang_name').'已经打包！');
        }
		
        $Pushorder = M("Pushorder",C('DB_PRS'),C('DB_DEPOT'));
        $Goods = M("Pushordergoods",C('DB_PRS'),C('DB_DEPOT'));
        $where = array();

        $where['order_no'] = $orderno;
        if ($Pushorder->where($where)->count() == 0) {
            alert('0', C('scanorder.lang_name').'不存在！');
        }
        if (M("Printorder",C('DB_PRS'),C('DB_DEPOT'))->where($where)->getField('is_inout') >= 1) {
            alert('0', '该'.C('scanorder.lang_name').'已经出库！');
        }
        if(M("Intercept_order",C('DB_PRS'),C('DB_DEPOT'))->where($where)->count() >= 1){
            alert('0', '注意：该'.C('scanorder.lang_name').'已被拦截！不能打包！');
        }
        $order_info = $Pushorder->where($where)->find();
		$order_id=$order_info['id'];
		$box_no=$order_info['box_no'];

        $result = $Goods->where("order_id='$order_id'")->select();
		
        if (count($result) == 0) {
            alert('0', '该'.C('scanorder.lang_name').'没有商品');
        }else{
			foreach($result as $k=>$v){
				$barcode=M('Goods',C('DB_PRS'),C('DB_DEPOT'))->field('bar_code')->where('goods_no="'.$v['goods_no'].'"')->find();
				$result[$k]['bar_code']=$barcode['bar_code'];
			}
			$return=array();
			$return['flag']=1;
			$return['box_no']=$box_no;
			$return['data']=$result;
			$this->ajaxReturn($return);
		}
    }

    public function paking_package()
    {
        if (I("get.index") == '') {
            alert('0', '请输入耗材条形码！');
        }
        $where['pn'] = I("get.index");
        $Pack = M("PackageMaterial",C('DB_PRS'),C('DB_DEPOT'));
        $result = $Pack->where($where)->find();
		// echo $Pack->getlastsql();
		// die;
        if (count($result) == 0) {
            alert('0', '耗材不存在！');
        }
        alert('1', $result);
    }

    public function packing_post()
    {
        $P = M("Packing",C('DB_PRS'),C('DB_DEPOT'));
        if (I("post.package") == '') {
            alert('0', '操作有误！');
        }
		$orderno = I("post.order_no");
		$orderno=$this->mailno_status($orderno);
		
        $data['order_no'] = $orderno;
        if($P->where("order_no='{$data['order_no']}'")->count()>=1){
            alert(0,'该'.C('scanorder.lang_name').'已经打包！');
        }
        $package = ltrim(I("post.package"), ',');
        $package = explode(',', $package);
        $new_arr = array();
        $new_count = array();
        foreach ($package as $v) {
            if (in_array($v, $new_arr)) {
                $index = array_search($v, $new_arr);
                $new_count[$index] = $new_count[$index] + 1;
            } else {
                $new_arr[] = $v;
                $new_count[] = 1;
            }
        }
        $data['all_pack_pn'] = implode(',', $new_arr);
        $data['all_pack_count'] = implode(',', $new_count);
        $data['order_no'] = $orderno;
        $vv = M("package_material",C('DB_PRS'),C('DB_DEPOT'));
        foreach ($new_arr as $k => $v) {///减去耗材数量
            $id = $vv->where("pn='$v'")->getField('id', true);
            foreach ($id as $i) {
                $count = $vv->where("id='$i'")->getField('quantity-a_quantity as count');
                if ($count >= $new_count[$k]) {
                    $vv->where("id='$i'")->setInc('a_quantity', $new_count[$k]);
                    break 1;
                } else {
                    $vv->where("id='$i'")->setInc('a_quantity', $count);
                    $new_count[$k] = $new_count[$k] - $count;
                }
            }
        }
        $tiji=0;
        foreach($id as $m){//计算耗材的体积
            $n_v=$vv->where("id='$m'")->getField('l_w_h');
            $n_v=explode('_',$n_v);
            $tiji=$tiji+$n_v[0]*$n_v[1]*$n_v[2];
        }
        $data['pack_v']=$tiji;
        if ($P->add($data)) {
            alert('1', I("post.order_no"));
        } else {
            alert('0', '操作失败');
        }
    }

    //////////称重
    public function weighed(){
        $weight=I("post.weight");
		$green=I('green');
		
        $order_no=I("post.order_no");
		$order_no=$this->mailno_status($order_no);
		
        $P=M("Packing",C('DB_PRS'),C('DB_DEPOT'));
        if ($weight == '') {
            alert('0', '操作有误！');
        }
        if(!is_numeric($weight)){
            alert('0', '重量必须为数字！');
        }
        $data['order_no'] = $order_no;
        if(M("Pushorder",C('DB_PRS'),C('DB_DEPOT'))->where("order_no='{$data['order_no']}'")->count()==0){
            alert(0,'该'.C('scanorder.lang_name').'不存在！');
        }
		if($green!=1){
			if($P->where("order_no='{$data['order_no']}'")->count()==0){
				alert(0,'该'.C('scanorder.lang_name').'还没有打包！');
			}
			if($P->where("order_no='{$data['order_no']}' and pack_weight is null")->count()<=0){
				alert(0,'该包裹已经称重！');
			}
		}else{
			if($P->where("order_no='{$data['order_no']}' and pack_weight is not null ")->count()>0){
				alert(0,'该包裹已称重！');
			}
		}
		
        
        $Pushorder = M("Pushorder",C('DB_PRS'),C('DB_DEPOT'));
        if($Pushorder->where("order_no='{$order_no}'")->getField('trade_model')==1){//跨境
            $return=$this->get_method();
        }
			$data['pack_weight']=$weight;
			$has_info=$P->where("order_no='{$order_no}'")->find();
			if(empty($has_info)){
				$data['all_pack_pn'] = 123;
				$data['all_pack_count'] = 1;
				$data['pack_v']=120000;
				$add_id=$P->add($data);
				alert(1,'操作成功！');
			}else{
				$res_save=$P->where("order_no='{$order_no}'")->save($data);
				if($res_save!==false){
					alert(1,'操作成功！');
				}
				else{
					alert(0,'操作失败！');
				}
			}
    }
	//称重加快递费用录入-备份
   /*  public function weighed(){
        $weight=I("post.weight");
		$green=I('green');
		
        $order_no=I("post.order_no");
		$order_no=$this->mailno_status($order_no);
		$g=M("Pushordergoods",C('DB_PRS'),C('DB_DEPOT'));
        $P=M("Packing",C('DB_PRS'),C('DB_DEPOT'));
        if ($weight == '') {
            alert('0', '操作有误！');
        }
        if(!is_numeric($weight)){
            alert('0', '重量必须为数字！');
        }
        $data['order_no'] = $order_no;
        if(M("Pushorder",C('DB_PRS'),C('DB_DEPOT'))->where("order_no='{$data['order_no']}'")->count()==0){
            alert(0,'该'.C('scanorder.lang_name').'不存在！');
        }
		// dump(I());
		// die;
		if($green!=1){
			if($P->where("order_no='{$data['order_no']}'")->count()==0){
				alert(0,'该'.C('scanorder.lang_name').'还没有打包！');
			}
		}
        if($P->where("order_no='{$data['order_no']}' and pack_weight is null")->count()<=0){
            alert(0,'该包裹已经称重！');
        }
        $Pushorder = M("Pushorder",C('DB_PRS'),C('DB_DEPOT'));
        if($Pushorder->where("order_no='{$order_no}'")->getField('trade_model')==1){//跨境
            $return=$this->get_method();
        }
        $data['pack_weight']=$weight;
		$res_save=$P->where("order_no='{$order_no}'")->save($data);
        if($res_save!==false){
			//计算快递费用-begin 50507602507487  50507601507866
			$pushorder=M("Pushorder",C('DB_PRS'),C('DB_DEPOT'));
			$map_pushorder['order_no']=$data['order_no'];
			$pushorder_info=$pushorder->where($map_pushorder)->find();//订单信息
			//调用快递费用函数
			$make_status=make_emsfee($pushorder_info['logiscompany_name'],$pushorder_info['province'],$weight);
			if($make_status['status']){
				$g_info=$g->field('goods_no')->where(array('order_id'=>$pushorder_info['id']))->find();
				$merchant_code=substr($g_info['goods_no'],0,9);//商家编码
				$make_status_rate=make_emsfee($pushorder_info['logiscompany_name'],$pushorder_info['province'],$weight,$merchant_code);
				
				$ems_fee=$make_status['fee'];
				$ems_fee_rate=$make_status_rate['fee'];
				$res_fee=$pushorder->where($map_pushorder)->setField('ems_fee',$ems_fee);//更新快递费用信息
				$res_fee=$pushorder->where($map_pushorder)->setField('ems_fee_rate',$ems_fee_rate);//更新快递费用信息
				//计算快递费用-end
				alert(1,'操作成功！');
			}else{
				alert(0,$make_status['message']);
			}
        }
        else{
            alert(0,'操作失败！');
        }
    } */
    public function weighting(){
		$mailno_status=C('base_config.mailno_status');
		if($mailno_status==1){
			C('scanorder.lang_name','面单');
		}else{
			C('scanorder.lang_name','订单');
		}
        $this->display();
    }
	
	//出库接口（更新出库信息）
	private function get_method(){
		// $status=M('Pushorder',C('DB_PRS'),C('DB_DEPOT'))->where(array('order_no'=>I("post.order_no")))->setField('is_delivery',1);
		$order_no=I("post.order_no");
		$order_no=$this->mailno_status($order_no);
		if($status!==false){
			$url=C('BASE_CONFIG.get_method');//更新出库信息

			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

			//post传值数据
			curl_setopt($ch, CURLOPT_POST, 1);
			//post的变量
			curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('order_no'=>$order_no)));
			$output = curl_exec($ch);
			curl_close($ch);
			return json_decode($output,true);
		}else{
			// M('Pushorder')->where(array('order_no'=>I("post.order_no")))->setField('is_delivery',0);//回滚操作
			$this->error('更新出库信息出错，请检查程序');
		}
    }
}